﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Globalization;
using Sistema_de_Gestión_de_Correspondencia.Models;
using PagedList;

namespace Sistema_de_Gestión_de_Correspondencia.Controllers
{
    [Authorize(Roles = "Administrador")]
    public class MembershipController : Controller
    {
        private SGCEntities db = new SGCEntities();
        //
        // GET: /Membership/
        public ActionResult Index(int page = 0, string s = "")
        {
            int pageSize = 9;
            MembershipUserCollection members = Membership.GetAllUsers();
            MembershipUserCollection model = new MembershipUserCollection();
            ViewBag.S = s;
            

            if (!String.IsNullOrEmpty(s))
            {
                s = s.ToUpper();
                foreach (MembershipUser user in members)
                {
                    if ((user.UserName != null && user.UserName.ToUpper().Contains(s)) || (user.Email != null && user.Email.ToUpper().Contains(s)) || (user.Comment != null && user.Comment.ToUpper().Contains(s)))
                    {
                        model.Add(user);
                        
                    }
                }
                ViewBag.cont = model.Count;
            }
            else
            {
                int cant;
                int pageTmp = page;

                model = Membership.GetAllUsers(pageTmp, pageSize, out cant);

                ViewBag.Paginacion = true;
                ViewBag.PageCount = Math.Ceiling((decimal)cant/(decimal)pageSize);
                ViewBag.PageNumber = page;
                if (page > 0)
                    ViewBag.HasPreviousPage = true;
                else
                    ViewBag.HasPreviousPage = false;
                if (page < (ViewBag.PageCount - 1))
                    ViewBag.HasNextPage = true;
                else
                    ViewBag.HasNextPage = false;
            }            
            return View(model);
        }

        public ActionResult Exito()
        {
            return View();
        }
        //
        // GET: /UserAccount/Create
        public ActionResult Create()
        {
            ViewData["PasswordLength"] = Membership.MinRequiredPasswordLength;
            return View();
        }

        //
        // POST: /Membership/Create
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string userName, string email, string password, string confirmPassword)
        {
            try
            {
                ViewData["PasswordLength"] = Membership.MinRequiredPasswordLength;

                if (ValidateRegistration(userName, email, password, confirmPassword))
                {
                    // Attempt to register the user
                    MembershipUser user = Membership.CreateUser(userName, password, email);

                    if (user != null)
                    {
                        return RedirectToAction("Edit", "Membership", new { id = user.ProviderUserKey });
                    }
                    else
                    {
                        ModelState.AddModelError("_FORM", "Error creando usuario");
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("_FORM", ex.Message);
            }

            // If we got this far, something failed, redisplay form
            return View();
        }

        private bool ValidateRegistration(string userName, string email, string password, string confirmPassword)
        {
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "Debe especificar un nombre de usuario.");
            }
            if (String.IsNullOrEmpty(email))
            {
                ModelState.AddModelError("email", "Debe especificar un correo.");
            }
            if (password == null || password.Length < Membership.MinRequiredPasswordLength)
            {
                ModelState.AddModelError("password",
                    String.Format(CultureInfo.CurrentCulture,
                         "Debe especificar un password de {0} o más caracteres.",
                         Membership.MinRequiredPasswordLength));
            }
            if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", "El password y su confirmación no coinciden.");
            }
            return ModelState.IsValid;
        }

        //
        // GET: /Membership/Edit/5
        public ActionResult Edit(Guid id)
        {
            MembershipUser user = Membership.GetUser(id, false);
            return View(user);
        }

        //
        // POST: /UserAccount/Edit/5
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            try
            {
                MembershipUser user = Membership.GetUser(id, false);
                UpdateModel(user);

                foreach (String role in Roles.GetAllRoles())
                {
                    if (collection[role].Contains("true"))
                    {
                        if (!Roles.IsUserInRole(user.UserName, role)) Roles.AddUserToRole(user.UserName, role);
                    }
                    else
                    {
                        if (Roles.IsUserInRole(user.UserName, role)) Roles.RemoveUserFromRole(user.UserName, role);
                    }
                }

                Membership.UpdateUser(user);

                return RedirectToAction("Exito");
            }
            catch (Exception ex)
            {
                ViewData.ModelState.AddModelError("_FORM", ex.Message);
                return View();
            }
        }
        //
        // GET: /Membership/Detail/5
        public ActionResult Detail(Guid id)
        {
            MembershipUser user = Membership.GetUser(id, false);
            return View(user);
        }

        public ActionResult Delete(Guid id)
        {
            MembershipUser user = Membership.GetUser(id, false);
            return View(user);
        }

        //
        // POST: /CuentaCorreo/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(Guid id)
        {
            MembershipUser user = Membership.GetUser(id, false);
            List<Correo> correos = db.Correos.Where(c => c.FK_idUsuario == id).ToList();
            foreach (Correo correo in correos)
            {
                db.delCorreo(correo.idCorreo);
            }
            Membership.DeleteUser(user.UserName, true);
            return RedirectToAction("Exito");
        }
    }
}
